<template>
  <div class="dict-page">
    <el-row :gutter="16">
      <el-col :span="8">
        <el-card>
          <div class="header">
            <span>字典类型</span>
            <el-button type="primary" link @click="openTypeDialog()">新增</el-button>
          </div>
          <el-table ref="typeTableRef" :data="typeList" height="560" highlight-current-row :row-class-name="typeRowClassName" @row-click="onTypeSelect">
            <el-table-column prop="dictName" label="名称" min-width="120" />
            <el-table-column prop="dictType" label="编码" min-width="120" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column width="120" label="操作">
              <template #default="{ row }">
                <el-button type="primary" link @click.stop="openTypeDialog(row)">编辑</el-button>
                <el-button type="danger" link @click.stop="removeType(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <div class="header">
            <span>字典项 - {{ currentType?.dictName || '未选择' }}</span>
            <el-button type="primary" :disabled="!currentType" link @click="openItemDialog()">新增</el-button>
          </div>
          <el-table :data="itemList" height="560">
            <el-table-column prop="dictLabel" label="标签" min-width="120" />
            <el-table-column prop="dictValue" label="值" min-width="120" />
            <el-table-column prop="dictSort" label="排序" width="80" />
            <el-table-column prop="isDefault" label="默认" width="80">
              <template #default="{ row }">
                <el-tag :type="row.isDefault ? 'warning' : 'info'">{{ row.isDefault ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column width="160" label="操作">
              <template #default="{ row }">
                <el-button type="primary" link @click.stop="openItemDialog(row)">编辑</el-button>
                <el-button type="danger" link @click.stop="removeItem(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="typeDialog.visible" :title="typeDialog.form.id ? '编辑字典类型' : '新增字典类型'" width="520">
      <el-form :model="typeDialog.form" label-width="100px">
        <el-form-item label="名称"><el-input v-model="typeDialog.form.dictName" /></el-form-item>
        <el-form-item label="编码"><el-input v-model="typeDialog.form.dictType" :disabled="!!typeDialog.form.id" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="typeDialog.form.status">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述"><el-input type="textarea" v-model="typeDialog.form.description" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialog.visible=false">取消</el-button>
        <el-button type="primary" @click="submitType">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="itemDialog.visible" :title="itemDialog.form.id ? '编辑字典项' : '新增字典项'" width="520">
      <el-form :model="itemDialog.form" label-width="100px">
        <el-form-item label="标签"><el-input v-model="itemDialog.form.dictLabel" /></el-form-item>
        <el-form-item label="值"><el-input v-model="itemDialog.form.dictValue" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="itemDialog.form.dictSort" :min="0" /></el-form-item>
        <el-form-item label="默认"><el-switch v-model="itemDialog.form.isDefault" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="itemDialog.form.status">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="itemDialog.visible=false">取消</el-button>
        <el-button type="primary" @click="submitItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDictTypes, getDictItems, createDictType, updateDictType, deleteDictType, createDictItem, updateDictItem, deleteDictItem } from '@/api/dict'

type DictType = { id?: string; dictName: string; dictType: string; status: number; description?: string }
type DictItem = { id?: string; dictType: string; dictLabel: string; dictValue: string; dictSort?: number; isDefault?: boolean; status?: number }

const typeList = ref<DictType[]>([])
const itemList = ref<DictItem[]>([])
const currentType = ref<DictType | null>(null)
const typeTableRef = ref()

const typeDialog = reactive({ visible: false, form: { dictName: '', dictType: '', status: 1, description: '' } as DictType })
const itemDialog = reactive({ visible: false, form: { dictType: '', dictLabel: '', dictValue: '', dictSort: 0, isDefault: false, status: 1 } as DictItem })

async function loadTypes() {
  const resp = await getDictTypes().catch(() => ({ data: [] }))
  typeList.value = (resp?.data || []) as DictType[]
  // 恢复或设置高亮当前行
  if (currentType.value) {
    const row = typeList.value.find(t => t.dictType === currentType.value!.dictType)
    if (row && typeTableRef.value?.setCurrentRow) {
      typeTableRef.value.setCurrentRow(row)
    }
  }
}

async function loadItems(typeCode: string) {
  const resp = await getDictItems(typeCode)
  itemList.value = resp.data || []
}

function onTypeSelect(row: DictType) {
  currentType.value = row
  if (typeTableRef.value?.setCurrentRow) typeTableRef.value.setCurrentRow(row)
  loadItems(row.dictType)
}

function openTypeDialog(row?: DictType) {
  if (row) typeDialog.form = { ...row }
  else typeDialog.form = { dictName: '', dictType: '', status: 1 }
  typeDialog.visible = true
}

async function submitType() {
  const form = typeDialog.form
  if (!form.dictName || !form.dictType) return ElMessage.error('名称/编码不能为空')
  const savedTypeCode = form.dictType
  if (form.id) await updateDictType(form.id, form)
  else await createDictType(form)
  ElMessage.success('保存成功')
  typeDialog.visible = false
  await loadTypes()
  // 定位到新保存/更新的类型并高亮
  const row = typeList.value.find(t => t.dictType === savedTypeCode)
  if (row) {
    currentType.value = row
    if (typeTableRef.value?.setCurrentRow) typeTableRef.value.setCurrentRow(row)
    await loadItems(row.dictType)
  }
}

async function removeType(row: DictType) {
  await ElMessageBox.confirm(`确认删除字典类型【${row.dictName}】？`, '提示')
  await deleteDictType(row.id as string)
  ElMessage.success('删除成功')
  if (currentType.value?.dictType === row.dictType) {
    currentType.value = null
    itemList.value = []
  }
  await loadTypes()
}

function openItemDialog(row?: DictItem) {
  if (!currentType.value) return
  if (row) itemDialog.form = { ...row }
  else itemDialog.form = { dictType: currentType.value.dictType, dictLabel: '', dictValue: '', dictSort: 0, isDefault: false, status: 1 }
  itemDialog.visible = true
}

async function submitItem() {
  const form = itemDialog.form
  if (!form.dictLabel || !form.dictValue) return ElMessage.error('标签/值不能为空')
  if (form.id) await updateDictItem(form.id, form)
  else await createDictItem(form)
  ElMessage.success('保存成功')
  itemDialog.visible = false
  if (currentType.value) await loadItems(currentType.value.dictType)
}

async function removeItem(row: DictItem) {
  await ElMessageBox.confirm(`确认删除字典项【${row.dictLabel}】？`, '提示')
  await deleteDictItem(row.id as string)
  ElMessage.success('删除成功')
  if (currentType.value) await loadItems(currentType.value.dictType)
}

onMounted(async () => {
  await loadTypes()
})

// 行样式：强化当前行高亮可见性
function typeRowClassName({ row }: { row: DictType }) {
  return currentType.value && row.dictType === currentType.value.dictType ? 'current-row' : ''
}
</script>

<style scoped>
.dict-page .header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

/* 强化 el-table 当前行样式 */
:deep(.el-table__body tr.current-row>td) {
  background-color: #ecf5ff !important;
}
:deep(.el-table__body tr:hover>td) {
  background-color: #f5f7fa;
}
</style>


